package com.ujiuye.Dao;


import com.ujiuye.entity.Product;
import com.ujiuye.util.DbutilsUtil;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.List;

public class ProductDao {
    QueryRunner qr = DbutilsUtil.getQr();

    public List<Product> select() {
        List<Product> list = null;
        String sql = "select * from tb_product";
        try {
            list = qr.query(sql, new BeanListHandler<>(Product.class));
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return list;
    }

    public Product getProductByPid(int pid) {
        Product product = null;
        String sql = "select * from tb_product where pid=?";
        try {
            product = qr.query(sql, new BeanHandler<>(Product.class), pid);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return product;
    }

    public int insert(String sname, int sage, String ssex, String semail) {
        int rows = 0;
        String sql = "insert into tb_product(sname,sage,ssex,semail) values(?,?,?,?)";
        try {
            rows = qr.update(sql, sname, sage, ssex, semail);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return rows;
    }

    public int update(int sid, String sname, int sage, String ssex, String semail) {
        int rows = 0;
        String sql = "update tb_product set sage=?,ssex=?,semail=?,sname=? where sid=?";
        try {
            rows = qr.update(sql, sage, ssex, semail, sname, sid);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return rows;
    }

    public int delete(String sname) {
        int rows = 0;
        String sql = "delete from tb_product where sname=?";
        try {
            rows = qr.update(sql, sname);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return rows;
    }
}
